<!--  -->
<template>
  <div>
    <a-modal
      width="50%"
      title="查看文件"
      :visible="viewFileVisible"
      :footer="null"
      @cancel="handleCancel"
    >
      <div class="pdf">
        <!-- <a target="_blank" :href="item | dealImageUrl" v-for="(item, index) in pdfData" :key="index">{{ pdfName[index] }}</a> -->
        <a v-for="(item, index) in pdfData" :key="index" @click="clickViewFile(item)">{{ pdfName[index] }}</a>
      </div>
      <div class="image">
        <img :src="item | dealImageUrl" v-for="(item, index) in imgData" :key="index">
      </div>
    </a-modal>
    <!-- 查看合同模板 -->
    <a-modal
      width="80%"
      :visible="modalVisible"
      :footer="null"
      @cancel="modalVisible = false"
    >
      <div class="pdf">
        <pdf
          ref="pdf"
          v-for="i in numPages"
          :key="i"
          :src="fileUrl"
          :page="i"
        ></pdf>
      </div>
    </a-modal>
    <pdfPreview :visible="pdfVisible" :url="fileUrl" @handleCancel="pdfVisible = false" />
  </div>
</template>

<script>
import pdf from 'vue-pdf-sign'
// 预览pdf用下面这个
import pdfPreview from '@/components/pdfPreview/index.vue'

export default {
  props: {
    viewFileVisible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    pdf,
    pdfPreview
  },
  data () {
    return {
      fileData: [],
      imgData: [],
      pdfData: [],
      pdfName: [],
      modalVisible: false,
      numPages: null,
      fileUrl: '',
      pdfVisible: false
    }
  },
  created () {
  },
  methods: {
    // 查看合同模板
    clickViewFile (fileUrl) {
      const url = this.$options.filters.dealImageUrl(fileUrl)
      // this.modalVisible = true
      // const loadingTask = pdf.createLoadingTask(url)
      // loadingTask.promise.then(pdf => {
      //   this.numPages = pdf.numPages
      //   this.initPage()
      // }).catch(err => {
      //   console.error('pdf 加载失败', err)
      //   this.initPage()
      // })
      this.pdfVisible = true
      this.fileUrl = url
    },
    initPage () {
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      }, 200)
    },
    // 处理数据
    handleData (viewFileData) {
      this.imgData = []
      this.pdfData = []
      this.fileData = viewFileData.fileUrl.split(',')
      this.pdfName = viewFileData.fileName.split(',')
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      // const formatPdf = /(\.(pdf))$/i
      this.fileData.forEach(item => {
        if (formatImg.test(item)) {
          this.imgData.push(item)
        } else {
          this.pdfData.push(item)
        }
        // if (formatPdf.test(item)) {
        //   this.pdfData.push(item)
        // }
      })
    },
    // 关闭弹窗
    handleCancel () {
      this.$emit('closeViewFile')
    }
  }
}
</script>
<style scoped lang="less">
  .pdf {
    margin: 0 auto;
    text-align: center;
  }
  .image {
    img {
      display: block;
      width: 80%;
      margin: 10px auto;
    }
  }
</style>
